<template>
	<div id="add-picture-view">
		<h2 style="margin-bottom: 16px">
			{{ route.query?.id ? '编辑图片' : '创建图片' }}
		</h2>
		<a-typography-paragraph v-if="spaceId" type="secondary" style="margin-bottom: 16px">
			保存至空间：<a :href="`/space/${spaceId}`" target="_blank">{{ spaceId }}</a>
		</a-typography-paragraph>
		<a-typography-paragraph v-else type="secondary" style="margin-bottom: 16px">
			上传至公共图库（需审核）
		</a-typography-paragraph>
		<!-- 选择上传方式 -->
		<a-tabs v-model:activeKey="uploadType">
			<a-tab-pane key="file" tab="文件上传">
				<!-- 图片上传组件 -->
				<FilePictureUpload :picture="picture" :spaceId="spaceId" :onSuccess="onSuccess" />
			</a-tab-pane>
			<a-tab-pane key="url" tab="URL上传">
				<!-- 图片链接上传组件 -->
				<UrlPictureUpload :picture="picture" :spaceId="spaceId" :onSuccess="onSuccess" />
			</a-tab-pane>
		</a-tabs>
		<!-- 图片裁剪组件 -->
		<div v-if="picture" class="edit-bar">
			<a-space size="middle">
				<a-button :icon="h(EditOutlined)" @click="doEditPicture">编辑图片</a-button>
				<a-tooltip v-if="!canAIOutPaint" title="图片格式、尺寸或大小不符合AI扩图要求">
					<a-button type="primary" :icon="h(FullscreenOutlined)" disabled>AI 扩图</a-button>
				</a-tooltip>
				<a-button v-else type="primary" :icon="h(FullscreenOutlined)" @click="doImageOutPainting">AI 扩图</a-button>
			</a-space>
		</div>
		<ImageCropper
			ref="imageCropperRef"
			:imageUrl="picture?.url"
			:picture="picture"
			:spaceId="spaceId"
			:space="space"
			:onSuccess="onCropSuccess"
		/>
		<ImageOutPaintingModal
			ref="imageOutPaintingModalRef"
			:picture="picture"
			:spaceId="spaceId"
			:onSuccess="onImageOutPaintingSuccess"
		/>

		<!-- 图片信息表单 -->
		<a-form v-if="picture" layout="vertical" name="pictureForm" :model="pictureForm" @finish="handleSubmit">
			<a-form-item name="name" label="名称">
				<a-input v-model:value="pictureForm.name" placeholder="输入名称" allow-clear />
			</a-form-item>
			<a-form-item name="introduction" label="简介">
				<a-textarea
					v-model:value="pictureForm.introduction"
					placeholder="输入简介"
					:auto-size="{ minRows: 2, maxRows: 4 }"
					allow-clear
				/>
			</a-form-item>
			<a-form-item name="category" label="分类">
				<a-auto-complete
					v-model:value="pictureForm.category"
					placeholder="输入分类"
					:options="filteredCategoryOptions"
					allow-clear
					@search="onCategorySearch"
					@select="onCategorySelect"
				/>
			</a-form-item>
			<a-form-item name="tags" label="标签">
				<a-select
					v-model:value="pictureForm.tags"
					mode="multiple"
					placeholder="选择标签"
					:options="filteredTagOptions"
					allow-clear
					show-search
					:filter-option="false"
					@search="onTagSearch"
					@select="onTagSelect"
					@deselect="onTagDeselect"
				/>
			</a-form-item>

			<a-form-item>
				<div v-if="!route.query?.id">
					<a-button type="primary" html-type="submit" style="width: 100%">创建</a-button>
				</div>
				<div v-else>
					<a-button type="primary" html-type="submit" style="width: 100%">更新</a-button>
				</div>
			</a-form-item>
		</a-form>
	</div>
</template>

<script setup lang="ts">
import { editPictureUsingPost, getPictureVoByIdUsingGet, listPictureTagCategoryUsingGet } from '@/api/pictureController'
import ImageCropper from '@/components/modal/ImageCropperModal.vue'
import FilePictureUpload from '@/components/picture/FilePictureUpload.vue'
import UrlPictureUpload from '@/components/picture/UrlPictureUpload.vue'
import { EditOutlined, FullscreenOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { computed, h, onMounted, reactive, ref, watchEffect } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import ImageOutPaintingModal from '@/components/modal/ImageOutPaintingModal.vue'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController'

const router = useRouter()

const picture = ref<API.PictureVO>()
const pictureForm = reactive<API.PictureEditRequest>({})
const uploadType = ref<'file' | 'url'>('file')

// 空间 id
const spaceId = computed(() => {
	return route.query?.spaceId
})

// 判断是否可以进行AI扩图
const canAIOutPaint = computed(() => {
	if (!picture.value) return false

	// 检查图像格式
	const supportedFormats = ['JPG', 'JPEG', 'PNG', 'HEIF', 'WEBP']
	const format = picture.value.picFormat?.toUpperCase()
	if (!format || !supportedFormats.includes(format)) {
		return false
	}

	// 检查图像大小（不超过10MB = 10 * 1024 * 1024 bytes）
	const maxSize = 10 * 1024 * 1024
	if (picture.value.picSize && picture.value.picSize > maxSize) {
		return false
	}

	// 检查图像分辨率（不低于512×512，不超过4096×4096）
	const width = picture.value.picWidth
	const height = picture.value.picHeight
	if (!width || !height) return false
	if (width < 512 || height < 512 || width > 4096 || height > 4096) {
		return false
	}

	return true
}) // 图片上传成功
const onSuccess = (newPicture: API.PictureVO) => {
	picture.value = newPicture
	pictureForm.name = newPicture.name
}

// 提交表单
const handleSubmit = async (values: API.UserLoginRequest) => {
	const pictureId = picture.value?.id
	if (!pictureId) {
		message.error('请先上传图片')
		return
	}

	const res = await editPictureUsingPost({
		id: pictureId,
		spaceId: spaceId.value as any,
		...values,
	})

	// 操作成功
	if (res.data.code === 0 && res.data.data) {
		// 先更新用户信息，再显示成功消息和跳转
		message.success('创建成功！')
		if (spaceId.value) {
			router.push(`/space/${spaceId.value}`)
		} else {
			router.push(`/picture/${pictureId}`)
		}
	} else {
		// 处理后端返回的错误
		message.error('创建失败' + res.data.message)
	}
}

// 分类选项
const categoryOptions = ref<{ value: string; label: string }[]>([])
// 标签选项
const tagOptions = ref<{ value: string; label: string }[]>([])

// 过滤后的分类选项
const filteredCategoryOptions = ref<{ value: string; label: string }[]>([])
// 过滤后的标签选项
const filteredTagOptions = ref<{ value: string; label: string }[]>([])

// 分类搜索关键词
const categorySearchValue = ref('')
// 标签搜索关键词
const tagSearchValue = ref('')

// 防抖定时器
let categorySearchTimer: number | null = null
let tagSearchTimer: number | null = null

// === 分类相关功能 ===
// 分类搜索（带防抖）
const onCategorySearch = (searchText: string) => {
	categorySearchValue.value = searchText

	// 清除之前的定时器
	if (categorySearchTimer) {
		clearTimeout(categorySearchTimer)
	}

	// 设置新的防抖定时器
	categorySearchTimer = setTimeout(() => {
		filterCategoryOptions(searchText)
	}, 300) // 300ms 防抖延迟
}

// 过滤分类选项
const filterCategoryOptions = (searchText: string) => {
	if (!searchText) {
		filteredCategoryOptions.value = categoryOptions.value
	} else {
		const searchLower = searchText.toLowerCase()
		filteredCategoryOptions.value = categoryOptions.value.filter((option) => {
			// 支持包含匹配、大小写不敏感
			return option.label.toLowerCase().includes(searchLower) || option.value.toLowerCase().includes(searchLower)
		})
	}
}

// 分类选择
const onCategorySelect = (value: string) => {
	pictureForm.category = value
	categorySearchValue.value = ''
}

// === 标签相关功能 ===
// 标签搜索（带防抖）
const onTagSearch = (searchText: string) => {
	tagSearchValue.value = searchText

	// 清除之前的定时器
	if (tagSearchTimer) {
		clearTimeout(tagSearchTimer)
	}

	// 设置新的防抖定时器
	tagSearchTimer = setTimeout(() => {
		filterTagOptions(searchText)
	}, 300) // 300ms 防抖延迟
}

// 过滤标签选项
const filterTagOptions = (searchText: string) => {
	if (!searchText) {
		filteredTagOptions.value = tagOptions.value
	} else {
		const searchLower = searchText.toLowerCase()
		// 过滤出匹配的标签选项
		filteredTagOptions.value = tagOptions.value.filter(
			(option) => option.label.toLowerCase().includes(searchLower) || option.value.toLowerCase().includes(searchLower)
		)
	}
} // 标签选择
const onTagSelect = (value: string) => {
	tagSearchValue.value = ''
}

// 标签取消选择
const onTagDeselect = (value: string) => {
	// 清除搜索关键词
	if (tagSearchValue.value === value) {
		tagSearchValue.value = ''
	}
}

// 获取分类和标签选项
const getTagCategoryOptions = async () => {
	const res = await listPictureTagCategoryUsingGet()

	if (res.data.code === 0 && res.data.data) {
		// 设置分类选项
		categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => {
			return {
				value: data,
				label: data,
			}
		})

		// 设置标签选项
		tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
			return {
				value: data,
				label: data,
			}
		})

		// 初始化过滤选项为全部选项
		filteredCategoryOptions.value = [...categoryOptions.value]
		filteredTagOptions.value = [...tagOptions.value]
	} else {
		// 处理后端返回的错误
		message.error('获取分类标签列表失败: ' + res.data.message)
	}
}

const route = useRoute()

// 获取老数据
const getOldPicture = async () => {
	// 获取到 id
	const id = route.query?.id
	// console.log('编辑模式 - 获取图片ID:', id)
	if (id) {
		try {
			const res = await getPictureVoByIdUsingGet({ id: id as any })
			if (res.data.code === 0 && res.data.data) {
				const data = res.data.data
				picture.value = data
				pictureForm.name = data.name
				pictureForm.introduction = data.introduction
				pictureForm.category = data.category
				pictureForm.tags = data.tags
			} else {
				console.error('获取图片数据失败:', res.data.message)
			}
		} catch (error) {
			console.error('获取图片数据出错:', error)
		}
	}
}

// 图片编辑器引用
const imageCropperRef = ref()
// 编辑图片
const doEditPicture = async () => {
	imageCropperRef.value?.openModal()
}

// 编辑成功事件
const onCropSuccess = (newPicture: API.PictureVO) => {
	picture.value = newPicture
	message.success('图片编辑成功')
	// 关闭弹窗
	imageCropperRef.value?.closeModal()
}

// AI 扩图弹窗引用
const imageOutPaintingModalRef = ref()
// 打开 AI 扩图弹窗
const doImageOutPainting = () => {
	imageOutPaintingModalRef.value?.openModal()
}
// AI 扩图成功事件
const onImageOutPaintingSuccess = (newPicture: API.PictureVO) => {
	picture.value = newPicture
	message.success('AI 扩图成功')
	// 关闭弹窗
	imageOutPaintingModalRef.value?.closeModal()
}

onMounted(() => {
	getTagCategoryOptions()
	getOldPicture()
})

// 获取空间信息
const space = ref<API.SpaceVO>()
const fetchSpace = async () => {
	if (spaceId.value) {
		const res = await getSpaceVoByIdUsingGet({ id: spaceId.value as any })
		if (res.data.code === 0 && res.data.data) {
			space.value = res.data.data
		} else {
			message.error('获取空间信息失败: ' + res.data.message)
		}
	}
}

watchEffect(() => {
	fetchSpace()
})
</script>

<style scoped lang="scss">
#add-picture-view {
	max-width: 720px;
	margin: 0 auto;

	// 表单项间距优化
	.ant-form-item {
		margin-bottom: 24px;
	}

	// 按钮样式优化 - 统一所有按钮大小
	.ant-btn {
		height: 40px;
		font-size: 14px;
		font-weight: 500;
	}

	// 表单提交按钮特殊样式
	.ant-btn-primary[html-type='submit'] {
		height: 48px;
		font-size: 16px;
		font-weight: 500;
	}

	// 编辑按钮样式
	.edit-bar {
		text-align: center;
		margin: 16px 0;

		.ant-btn {
			min-width: 120px;
		}
	}
}
</style>
